#!/usr/bin/env python3
"""
调试BudgetAgent和WeatherAgent协商过程的脚本
通过详细日志和步骤分解来观察协商流程
"""

import requests
import json
import time
import logging
from datetime import datetime

# 配置详细调试日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('negotiation_debug.log'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger('NegotiationDebug')

class NegotiationDebugger:
    """协商过程调试器"""
    
    def __init__(self):
        self.agents = {
            "coordinator": "http://localhost:7006",
            "budget": "http://localhost:7007", 
            "weather": "http://localhost:7003",
            "travel": "http://localhost:7004"
        }
        self.debug_steps = []
    
    def check_agents_status(self):
        """检查所有Agent的状态"""
        print("🔍 检查Agent状态...")
        logger.info("开始检查所有Agent状态")
        
        for name, url in self.agents.items():
            try:
                response = requests.get(f"{url}/status", timeout=5)
                status = "✅ 在线" if response.status_code == 200 else f"❌ 状态码: {response.status_code}"
                print(f"  {name.upper()}Agent ({url}): {status}")
                logger.info(f"{name}Agent状态: {status}")
            except Exception as e:
                print(f"  {name.upper()}Agent ({url}): ❌ 离线 - {e}")
                logger.error(f"{name}Agent离线: {e}")
    
    def simulate_budget_conflict_scenario(self):
        """模拟预算冲突场景"""
        print("\n" + "="*80)
        print("🎭 模拟预算冲突协商场景")
        print("="*80)
        
        # 场景设置：低预算 + 恶劣天气
        scenario = {
            "user_requirements": {
                "destination": "欧洲",
                "budget": "150欧元",  # 故意设置很低的预算
                "duration": "3天",
                "preferences": ["户外摄影", "历史景点"],
                "weather_sensitivity": "high"
            },
            "expected_conflicts": [
                "预算严重不足",
                "天气条件增加成本",
                "户外偏好与预算限制冲突"
            ]
        }
        
        logger.info(f"场景设置: {json.dumps(scenario, ensure_ascii=False, indent=2)}")
        print(f"📋 场景参数:")
        print(f"  🌍 目的地: {scenario['user_requirements']['destination']}")
        print(f"  💰 预算: {scenario['user_requirements']['budget']} (故意设置很低)")
        print(f"  📅 时长: {scenario['user_requirements']['duration']}")
        print(f"  🎯 偏好: {scenario['user_requirements']['preferences']}")
        
        return scenario
    
    def step1_trigger_budget_analysis(self, scenario):
        """步骤1: 触发BudgetAgent分析"""
        print(f"\n🔸 步骤1: 向BudgetAgent发送协作请求")
        logger.info("步骤1: 开始BudgetAgent分析")
        
        collaboration_request = {
            "type": "collaboration_request",
            "user_requirements": scenario["user_requirements"],
            "collaboration_context": {
                "purpose": "budget_conflict_detection",
                "debug_mode": True
            }
        }
        
        payload = {
            "message": {
                "content": {
                    "text": json.dumps(collaboration_request, ensure_ascii=False)
                }
            }
        }
        
        try:
            print(f"  📤 发送请求到 BudgetAgent...")
            logger.debug(f"发送给BudgetAgent的payload: {json.dumps(payload, ensure_ascii=False, indent=2)}")
            
            response = requests.post(
                f"{self.agents['budget']}/a2a/tasks/send",
                json=payload,
                timeout=15
            )
            
            print(f"  📥 BudgetAgent响应状态: {response.status_code}")
            logger.info(f"BudgetAgent响应状态: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                logger.debug(f"BudgetAgent原始响应: {json.dumps(result, ensure_ascii=False, indent=2)}")
                
                # 解析响应
                if "artifacts" in result and len(result["artifacts"]) > 0:
                    budget_response_text = result["artifacts"][0]["parts"][0]["text"]
                    budget_response = json.loads(budget_response_text)
                    
                    print(f"  💰 预算分析结果:")
                    print(f"    - 预算状态: {budget_response.get('budget_data', {}).get('budget_status', 'unknown')}")
                    
                    conflicts = budget_response.get('potential_conflicts', [])
                    print(f"    - 检测到冲突: {len(conflicts)}个")
                    
                    for i, conflict in enumerate(conflicts, 1):
                        print(f"      {i}. {conflict.get('type', 'unknown')}: {conflict.get('description', 'no description')}")
                        print(f"         严重程度: {conflict.get('severity', 'unknown')}")
                        if 'amount' in conflict:
                            print(f"         影响金额: {conflict['amount']}欧元")
                    
                    logger.info(f"检测到{len(conflicts)}个预算冲突")
                    self.debug_steps.append({
                        "step": 1,
                        "action": "budget_analysis",
                        "conflicts_detected": len(conflicts),
                        "conflicts": conflicts,
                        "timestamp": datetime.now().isoformat()
                    })
                    
                    return budget_response
                else:
                    print(f"  ❌ BudgetAgent响应格式异常")
                    logger.error("BudgetAgent响应格式异常")
                    return None
            else:
                print(f"  ❌ BudgetAgent请求失败: {response.status_code}")
                print(f"  错误信息: {response.text}")
                logger.error(f"BudgetAgent请求失败: {response.status_code}, {response.text}")
                return None
                
        except Exception as e:
            print(f"  ❌ BudgetAgent通信异常: {e}")
            logger.error(f"BudgetAgent通信异常: {e}")
            return None
    
    def step2_monitor_budget_to_weather_negotiation(self, budget_response):
        """步骤2: 监控BudgetAgent向WeatherAgent发起的协商"""
        print(f"\n🔸 步骤2: 监控BudgetAgent -> WeatherAgent 协商")
        logger.info("步骤2: 开始监控Agent间协商")
        
        # 检查BudgetAgent是否会主动发起协商
        conflicts = budget_response.get('potential_conflicts', [])
        high_severity_conflicts = [c for c in conflicts if c.get('severity') == 'high' or c.get('severity') == 'critical']
        
        if high_severity_conflicts:
            print(f"  🚨 检测到{len(high_severity_conflicts)}个高严重级别冲突")
            print(f"  💡 预期BudgetAgent会主动向WeatherAgent发起协商...")
            
            # 等待一段时间让协商发生
            print(f"  ⏳ 等待协商过程...")
            time.sleep(2)
            
            # 检查WeatherAgent是否收到协商请求
            return self.check_weather_agent_negotiation_logs()
        else:
            print(f"  ℹ️ 未检测到高严重级别冲突，可能不会触发主动协商")
            return None
    
    def check_weather_agent_negotiation_logs(self):
        """检查WeatherAgent是否收到协商请求"""
        print(f"  🔍 尝试通过测试请求检验WeatherAgent协商处理...")
        
        # 模拟BudgetAgent发送给WeatherAgent的协商请求
        test_negotiation = {
            "type": "negotiation_request",
            "sender": "BudgetAgent",
            "negotiation_context": {
                "issue": "budget_shortfall",
                "severity": "high",
                "requested_cost_reduction": 100
            },
            "proposals": [
                {
                    "option": "adjust_travel_dates",
                    "description": "调整旅行日期以降低成本",
                    "expected_savings": 60
                },
                {
                    "option": "increase_indoor_ratio", 
                    "description": "增加室内活动比例，减少交通成本",
                    "expected_savings": 40
                }
            ]
        }
        
        payload = {
            "message": {
                "content": {
                    "text": json.dumps(test_negotiation, ensure_ascii=False)
                }
            }
        }
        
        try:
            print(f"  📤 发送测试协商请求到WeatherAgent...")
            response = requests.post(
                f"{self.agents['weather']}/a2a/tasks/send",
                json=payload,
                timeout=10
            )
            
            print(f"  📥 WeatherAgent响应状态: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                print(f"  ✅ WeatherAgent成功处理协商请求")
                logger.info("WeatherAgent协商请求处理成功")
                
                # 尝试解析响应
                if "artifacts" in result:
                    weather_response_text = result["artifacts"][0]["parts"][0]["text"]
                    weather_response = json.loads(weather_response_text)
                    
                    print(f"  🌤️ WeatherAgent协商响应:")
                    print(f"    - 响应类型: {weather_response.get('type', 'unknown')}")
                    
                    if 'error' in weather_response:
                        print(f"    - ❌ 错误: {weather_response['error']}")
                        logger.warning(f"WeatherAgent协商处理错误: {weather_response['error']}")
                    else:
                        print(f"    - ✅ 协商处理成功")
                        logger.info("WeatherAgent协商处理成功")
                    
                    return weather_response
                    
            else:
                print(f"  ❌ WeatherAgent协商请求失败: {response.status_code}")
                logger.error(f"WeatherAgent协商请求失败: {response.status_code}")
                return None
                
        except Exception as e:
            print(f"  ❌ WeatherAgent协商通信异常: {e}")
            logger.error(f"WeatherAgent协商通信异常: {e}")
            return None
    
    def step3_analyze_negotiation_results(self, weather_response):
        """步骤3: 分析协商结果"""
        print(f"\n🔸 步骤3: 分析协商结果")
        
        if weather_response:
            print(f"  📊 协商成功完成")
            print(f"  📋 协商结果分析:")
            
            # 检查是否有协商建议
            if 'negotiation_points' in weather_response:
                negotiation_points = weather_response['negotiation_points']
                print(f"    - 协商建议数量: {len(negotiation_points)}")
                
                for point in negotiation_points:
                    target = point.get('target_agent', 'unknown')
                    topic = point.get('topic', 'unknown')
                    proposal = point.get('proposal', 'no proposal')
                    print(f"    - 针对{target}: {topic}")
                    print(f"      提案: {proposal}")
            
            # 检查冲突预测
            if 'potential_conflicts' in weather_response:
                conflicts = weather_response['potential_conflicts']
                print(f"    - 预测冲突: {len(conflicts)}个")
                
                for conflict in conflicts:
                    conflict_type = conflict.get('conflict_type', 'unknown')
                    severity = conflict.get('severity', 'unknown')
                    description = conflict.get('description', 'no description')
                    print(f"    - {conflict_type} ({severity}): {description}")
            
            logger.info("协商结果分析完成")
        else:
            print(f"  ❌ 协商未成功完成或响应为空")
            logger.warning("协商未成功完成")
    
    def generate_debug_report(self):
        """生成调试报告"""
        print(f"\n" + "="*80)
        print("📋 协商调试报告")
        print("="*80)
        
        print(f"🕒 调试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"📊 调试步骤数: {len(self.debug_steps)}")
        
        for step in self.debug_steps:
            print(f"\n步骤{step['step']}: {step['action']}")
            print(f"  时间: {step['timestamp']}")
            if 'conflicts_detected' in step:
                print(f"  检测到冲突: {step['conflicts_detected']}个")
        
        print(f"\n📝 详细日志已保存到: negotiation_debug.log")
        print(f"🔍 如需查看完整日志，请执行: tail -f negotiation_debug.log")

def main():
    """主函数"""
    print("🚀 启动BudgetAgent和WeatherAgent协商调试器")
    print("🎯 目标: 观察和分析Agent间的冲突协商过程")
    
    debugger = NegotiationDebugger()
    
    # 步骤0: 检查Agent状态
    debugger.check_agents_status()
    
    # 步骤1: 设置冲突场景
    scenario = debugger.simulate_budget_conflict_scenario()
    
    # 步骤2: 触发预算分析
    budget_response = debugger.step1_trigger_budget_analysis(scenario)
    
    if budget_response:
        # 步骤3: 监控协商过程
        weather_response = debugger.step2_monitor_budget_to_weather_negotiation(budget_response)
        
        # 步骤4: 分析结果
        debugger.step3_analyze_negotiation_results(weather_response)
    
    # 生成报告
    debugger.generate_debug_report()
    
    print(f"\n✅ 调试完成!")
    print(f"💡 建议: 查看生成的 negotiation_debug.log 文件获取完整的调试信息")

if __name__ == "__main__":
    main()